package com.lixin.web.netty;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Maps;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

/**
 * Description: 会话管理 每个节点只管理自己的channel
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-07-29 18:28:02
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-07-29     张李鑫                     1.0         1.0 Version
 */
@Component
public class UserSessionManager {

    private final BiMap<Integer, Channel> userSession = Maps.synchronizedBiMap(HashBiMap.create());
    private final BiMap<String, Integer> channelToUserCode = Maps.synchronizedBiMap(HashBiMap.create());


    /**
     * 当用户登录成功或者重连 用户便有了状态添加到有状态的容器中
     */
    public void addUserSession(Integer userId, Channel channel) {
        userSession.put(userId, channel);
        channelToUserCode.put(channel.id().asLongText(), userId);
    }

    /**
     * 根据userId获取channel
     *
     * @param userId
     * @return
     */
    public Channel getChannelByUserId(Integer userId) {
        return userSession.get(userId);
    }

    /**
     * 移除连接
     *
     * @param userId
     * @return
     */
    public void removeUserSession(Integer userId) {
        Channel removeChannel = userSession.remove(userId);
        if (removeChannel != null) {
            channelToUserCode.remove(removeChannel.id().asLongText());
        }
    }

    /**
     * 获取在线人数
     *
     * @return
     */
    public int getUserSessionCount() {
        return userSession.size();
    }


}
